<?php

/**
 * Smarty tag
 * Main in-place edit function
 *
 * prepares and assembles needed templates for js
 * @uses getJs(), getTemplate(), getDefaultParams(), getTriggerTemplate()
 * 
 * @param array $params
 * @param Smarty $template
 * @return string 
 */
function smarty_function_editable($params = array(), $template) {
    $trigger = getTriggerTemplate($params, $template);
    if (isset($params['only_trigger'])) {
        return $trigger;
    }
    $args = getDefaultParams($params);
    $tpl = getTemplate($args, $params, $template);

    return isset($params['no_trigger']) ? '' : $trigger . getJs($params, $tpl);
}

/**
 * Grab needed params from $param array, passed into smarty_function_editable
 * Extracts needed info from referenced object: model, id, value, key
 *
 * @param array $params
 * @return array 
 */
function getDefaultParams($params) {
    if (empty($params['source'])) {
        $source = !empty($params['default_value']) ? $params['default_value'] : '';	
    }
    else {
        $source = $params['source'];	
    }
    $item = $params['item'];
    return array(
        'model' => $item->getTableClass(),
        'id' => $item->id,
        'value' => $source ,
        'key' => $params['key']
    );
}

/**
 * Embed small js code, which performs needed checks and initialisations,
 * in order in-place edit can work properly
 * 
 * @var string $noJqMessage // message, that is displayed in alert box, if no jQuert lib found
 * 
 * @param array $params
 * @param string $tpl
 * @return string 
 */
function getJs($params, $tpl) {
    $noJqMessage = "jQuery library is not available at the page.";
    $js = <<<JS
    <script type="text/javascript">
        if('undefined' == typeof jQuery) {
            alert('{$noJqMessage}');
        }
        $(document).ready(function(){
            if('undefined' == typeof _ETpls) {
                _ETpls = {};
            }
            if('undefined' == typeof _EValues) {
                _EValues = {};
            }
            _ETpls['{$params['dom_id']}'] = '{$tpl}';
        });
    </script>    
JS;
    return $js;
}

/*
 * Trigger element. Element, that will open the in-place edit box after clicking on it
 * 
 * @param array $params
 * @param string $template
 * @return string 
 */
 
function getTriggerTemplate($params = array(), $template) {
    $dom_id = $params["dom_id"];
    $tamplate = <<<TPL
    <img class="trigger-{$params['dom_id']}" onClick="editInPlace('{$dom_id}');" src="{$template->getZendView()->baseUrl("common/images/edit.png")}" />
TPL;

    return $tamplate;
}

/**
 * Update in place js function name
 * 
 * generates corresponding field update function name used by javascript
 *
 * @param array $params
 * @return string 
 */
function getJsUpdateFunctionName($params = array()) {
    if (!isset($params['update_as'])) {
        return 'saveInPlace';
    }
    switch ($params['update_as']) {
        case 'reviewable':
            $jsFunction = 'updateInPlaceReviewable';
            break;
        case 'user_text':
            $jsFunction = 'updateInPlaceUserText';
            break;
        case 'place_text':
            $jsFunction = 'updateInPlacePlaceText';
            break;
        default:
            $jsFunction = 'saveInPlace'; 
            break;
    }
    
    return $jsFunction;
}

/**
 * Grab needed template, according to the object's value.
 * 
 * @param array $params // values for template
 * @param string $key
 * @return string 
 */
function getTemplate($args, $params, $template = null) {
    $updateJsFunction = getJsUpdateFunctionName($params);
    $value = trim($args['value']);
    $key = isset($params['type']) ? $params['type'] : 'default';
    $tpl_default = <<<TPL
        <span id="{$params['dom_id']}_edit">
            <input type="text" value="{$value}" class="value" />
            <button onClick="{$updateJsFunction}('{$params['dom_id']}', '{$args['model']}', '{$args['id']}', '{$args['key']}');">Save</button>
            <button onClick=cancelEditInPlace('{$params['dom_id']}');>Cancel</button>
        </span>        
TPL;
    $tpl_textarea = $template->getZendView()->partial('_editable_textarea.tpl', array(
        'rows' => isset($params['rows']) ? $params['rows'] : 80,
        'cols' => isset($params['cols']) ? $params['cols'] : 24,
        'dom_id' => $params['dom_id'],
        'id' => $args['id'],
        'key' => $args['key'],
        'value' => $args['value'],
        'model' => $args['model'],
        'updateJsFunction' => $updateJsFunction        
    ));

    $templates = array(
        'default' => $tpl_default,
        'textarea' => $tpl_textarea
    );

    $tpl = isset($templates[$key]) ? $templates[$key] : $templates['default'];
    $tpl = str_replace("'", "\'", $tpl); // js quotes
    return str_replace("\r", "", str_replace("\n", "", $tpl));;
}